//
// Created by chaseaishang on 23-5-10.
//

#include "SpriteRenderer.h"
#include "VertexBufferLayout.h"



SpriteRenderer::SpriteRenderer(std::string file_vs, std::string file_fs) {

    initRenderData(file_vs,file_fs);
}

SpriteRenderer::~SpriteRenderer() {

}

void SpriteRenderer::DrawSprite(const Texture &texture, glm::vec2 position, glm::vec2 size, GLfloat rotate, glm::vec3 color)
{

    texture.Bind(0);
    this->m_Shader->Bind();

    glm::mat4 model = glm::translate(glm::mat4(1.0f), {position,1.0f});


    model=glm::scale(model,glm::vec3(size,1.0f));
    // m_View=glm::lookAt(glm::vec3(0,0,0.5),glm::vec3(0,0,0),glm::vec3(0,1,0));
//    auto m_Proj=glm::ortho(0.0f, 800.0f, 0.0f, 600.0f, -1.0f, 1.0f);
    glm::mat4 mvp = m_view_proj  * model;


    m_Shader->SetUniformMat4f("u_MVP", mvp);
    //spriteColor
    m_Shader->SetUniform3f("spriteColor",color.r,color.g,color.b);



    m_Renderer->Draw(*m_quadVAO,*m_IndexBuffer,*m_Shader);







}

void SpriteRenderer::initRenderData(std::string file_vs, std::string file_fs)
{
    float positions[] = {
            0.0f, 0.0f,          0.0f, 0.0f, // 0
            1.0f, 0.0f,         1.0f, 0.0f,  // 1
            1.0f, 1.0f,      1.0f, 1.0f,    // 2
            0.0f, 1.0f,    0.0f, 1.0f,   // 3


    };
    unsigned int indices[] = {
            //front
            0, 1, 2,
            2, 3, 0,

    };
    GLCall(glEnable(GL_DEPTH_TEST));
    GLCall(glEnable(GL_BLEND));
    GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));

    m_quadVAO = std::make_unique<VertexArray>();

    m_VertexBuffer = std::make_unique<VertexBuffer>(positions, 4 * 4 * sizeof(float));
    VertexBufferLayout layout;
    layout.Push<float>(2);
    layout.Push<float>(2);
    m_quadVAO->AddBuffer(*m_VertexBuffer, layout);

    m_IndexBuffer = std::make_unique<IndexBuffer>(indices, 6);
//m_Shader=std::make_unique<Shader>();
    m_Shader = std::make_unique<Shader>(file_vs,file_fs);
    m_Shader->Bind();

    m_Shader->SetUniform1i("u_Texture", 0);








}

void SpriteRenderer::Set_viewProjection(glm::mat4 &view_proj)
{
    m_view_proj=view_proj;
}




